package com.neu.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.neu.pojo.User;
import com.neu.service.UserService;

/**
 * 用户管理Controller
 *
 * @author Admin
 */
@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request) {
        //代码编写处
        //创建ModelAndView
        ModelAndView modelAndView = new ModelAndView();
        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");
        if (ObjectUtils.isEmpty(user)) {
            // 放入jsp路径
            // 设置转向地址
            modelAndView.setViewName("index");
        } else {
            List<User> users = userService.getUsers();
            modelAndView.addObject("userList", users);
            // 设置转向地址
            modelAndView.setViewName("users");
        }
        return modelAndView; //请修改代码
    }

    /**
     * 跳转到addUser界面
     * @return
     */
    @RequestMapping("/toAddUser")
    public String toAddUser() {
        return "addUser";
    }

    /**
     * 添加用户请求
     * @param user
     * @return
     */
    @RequestMapping("/addUser")
    public String addUser(User user) {
        int i = userService.addUser(user);
        if (i > 0) {
            return "redirect:/users/index";
        } else {
            return "redirect:/users/addUser";
        }
    }

    /**
     * 跳转到回显到updateUser界面，并通过id查询被修改数据，回显到updateUser
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/toUpdateUser")
    public String toUpdateUser(int id, Model model) {
        User userById = userService.getUserById(id);
        model.addAttribute("user",userById);
        return "updateUser";
    }

    /**
     * 更新用户请求
     * @param user
     * @return
     */
    @RequestMapping("/updateUser")
    public String updateUser(User user) {
        int i = userService.updateUser(user);
        if (i > 0) {
            return "redirect:/users/index";
        } else {
            return "redirect:/users/updateUser";
        }
    }

    /**
     * 删除用户请求
     * @param id
     * @return
     */
    @RequestMapping("/deleteUserById/{id}")
    public String deleteUserById(@PathVariable("id") int id) {
        int i = userService.deleteUserById(id);
        if (i > 0) {
            return "redirect:/users/index";
        } else {
            return "redirect:/users/deleteUserById";
        }
    }
}